Page({
  data: {
    traceInfo: null,
    loading: true,
    error: null
  },

  onLoad: function(options) {
    const { traceId, batchId } = options;
    if (!traceId || !batchId) {
      this.setData({
        error: '缺少必要的溯源参数',
        loading: false
      });
      return;
    }
    this.getTraceInfo(traceId, batchId);
  },

  // 获取溯源详情数据
  getTraceInfo(traceId, batchId) {
    wx.showLoading({
      title: '加载溯源信息',
      mask: true
    });

    wx.request({
      url: 'http://107.151.248.212:8000/back/qrcode/detail',
      method: 'GET',
      data: {
        traceId: traceId,
        batchId: batchId
      },
      success: (res) => {
        wx.hideLoading();
        setTimeout(() => {
          if (res.data.code === 200) {
            this.setData({
              traceInfo: res.data.data,
              loading: false
            });
          } else {
            wx.showToast({
              title: res.data.message || '获取溯源信息失败',
              icon: 'none',
              duration: 3000,
              mask: true
            });
            this.setData({
              loading: false
            });
          }
        }, 200);
      },
      fail: (error) => {
        wx.hideLoading();
        setTimeout(() => {
          console.error('获取溯源详情失败：', error);
          wx.showToast({
            title: '网络请求失败，请重试',
            icon: 'none',
            duration: 3000,
            mask: true
          });
          this.setData({
            loading: false
          });
        }, 200);
      }
    });
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: [url]
    });
  },

  viewReport(e) {
    const reportUrl = e.currentTarget.dataset.report;
    if (reportUrl) {
      console.log('准备下载文件：', reportUrl);
      wx.downloadFile({
        url: reportUrl,
        success: function(res) {
          console.log('文件下载成功：', res);
          const filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            success: function(res) {
              console.log('打开文档成功');
            },
            fail: function(error) {
              console.error('打开文档失败', error);
              wx.showToast({
                title: '打开文档失败',
                icon: 'none'
              });
            }
          });
        },
        fail: function(error) {
          console.error('下载文件失败', error);
          wx.showToast({
            title: '下载文件失败',
            icon: 'none'
          });
        }
      });
    }
  }
}); 